﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace CommonNet48.Encrypt
{
    /// <summary>
    /// HmacSHA256加密帮助类
    /// </summary>
    public class HMACSHA256Helper
    {
        /// <summary>
        /// HmacSHA256加密(返回Hex字符串)
        /// </summary>
        /// <param name="data">待加密数据</param>
        /// <param name="key">加密Key</param>
        /// <returns></returns>
        public static string EncryptToHex(string data, string key)
        {
            string ret = string.Empty;
            using (HMACSHA256 eObj = new HMACSHA256(Encoding.UTF8.GetBytes(key)))
            {
                byte[] hash = eObj.ComputeHash(Encoding.UTF8.GetBytes(data));
                ret = string.Join("", hash.Select(t => t.ToString("X2")));
            }
            return ret;
        }

        /// <summary>
        /// HmacSHA256加密(返回Base64字符串)
        /// </summary>
        /// <param name="data">待加密数据</param>
        /// <param name="key">加密Key</param>
        /// <returns></returns>
        public static string EncryptToBase64(string data, string key)
        {
            string ret = string.Empty;
            using (HMACSHA256 eObj = new HMACSHA256(Encoding.UTF8.GetBytes(key)))
            {
                byte[] hash = eObj.ComputeHash(Encoding.UTF8.GetBytes(data));
                ret = Convert.ToBase64String(hash);
            }
            return ret;
        }
    }
}
